package com.zzyl.nursing.service.impl;


import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;

import com.zzyl.common.utils.AgeUtils;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住管理Service业务层处理
 *
 * @author zhangyan
 * @date 2025-05-24
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    //入住管理
    @Autowired
    private CheckInMapper checkInMapper;

    //老人信息
    @Autowired
    private ElderMapper elderMapper;

    //入住配置
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    //合同
    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住管理
     *
     * @param id 入住管理主键
     * @return 入住管理
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住管理列表
     *
     * @param checkIn 入住管理
     * @return 入住管理
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住管理
     *
     * @param dto 入住管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCheckIn(CheckInApplyDto dto) {
        try {
            //老人信息
            CheckInElderDto elderDto = dto.getCheckInElderDto();
            //家属信息
            List<ElderFamilyDto> familyDtoList = dto.getElderFamilyDtoList();
            //入住配置
            CheckInConfigDto configDto = dto.getCheckInConfigDto();
            //签约办理
            CheckInContractDto contractDto = dto.getCheckInContractDto();


            //校验老人是否已入住  如果已入住直接抛异常BaseException
            String idCardNo = elderDto.getIdCardNo();
            LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(elderDto.getIdCardNo() != null, Elder::getIdCardNo, elderDto.getIdCardNo());
            lambdaQueryWrapper.eq(Elder::getStatus, 4);
            Elder elder = elderMapper.selectOne(lambdaQueryWrapper);
            if (elder != null) {
                throw new BaseException("老人已入住");
            }
            //更新床位的状态
            Long bedId = configDto.getBedId();
            Bed bed = bedMapper.selectById(bedId);
            bed.setBedStatus(1);
            bedMapper.updateById(bed);
            //新增或更新老人elder
            elder = saveOrUpdateElder(elderDto, bed);
            //新增合同信息  合同号要求： HT+18位数字，例：HT202501011012590001
            saveContract(contractDto, elder, configDto);
            //新增入住信息  老人家属信息存到remark字段中
            CheckIn checkIn = saveCheckIn(configDto, familyDtoList, elder);
            //新增入住配置
            saveCheckInConfig(configDto, checkIn);
        } catch (BaseException e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    private void saveCheckInConfig(CheckInConfigDto configDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(configDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(configDto.getNursingLevelName());
        checkInConfig.setFeeStartDate(configDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(configDto.getFeeEndDate());
        checkInConfig.setDeposit(configDto.getDeposit());
        checkInConfig.setNursingFee(configDto.getNursingFee());
        checkInConfig.setBedFee(configDto.getBedFee());
        checkInConfig.setInsurancePayment(configDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(configDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(configDto.getOtherFees());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn saveCheckIn(CheckInConfigDto configDto, List<ElderFamilyDto> familyDtoList, Elder elder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(configDto.getStartDate());
        checkIn.setEndDate(configDto.getEndDate());
        checkIn.setNursingLevelName(configDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(familyDtoList));

        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void saveContract(CheckInContractDto contractDto, Elder elder, CheckInConfigDto configDto) {
        Contract contract = new Contract();
        //老人信息相关
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());

        //合同dto相关
        contract.setContractName(contractDto.getContractName());
        contract.setContractNumber(contractDto.getContractName());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setSignDate(contractDto.getSignDate());

        //HT+18位数字，例：HT202501011012590001
        contract.setAgreementPath("HT" + CodeGenerator.generateContractNumber());


        contract.setStartDate(configDto.getStartDate());
        contract.setEndDate(configDto.getEndDate());
        contract.setStatus(1);

        contractMapper.insert(contract);

    }

    private Elder saveOrUpdateElder(CheckInElderDto elderDto, Bed bed) {
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(elderDto.getIdCardNo() != null, Elder::getIdCardNo, elderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(lambdaQueryWrapper);
        boolean flag = false;
        if (elder == null) {
            flag = true;
            elder = new Elder();
        }
        elder.setName(elderDto.getName());
        elder.setImage(elderDto.getImage());
        elder.setIdCardNo(elderDto.getIdCardNo());
        elder.setSex(elderDto.getSex());
        elder.setStatus(4);
        elder.setPhone(elderDto.getPhone());
        elder.setBirthday(elderDto.getBirthday());
        elder.setAddress(elderDto.getAddress());
        elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
        elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
//        BeanUtils.copyBeanProp(elderDto,elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        if (flag) {
            elderMapper.insert(elder);
        } else {
            elderMapper.updateById(elder);
        }
        return elder;
    }

    /**
     * 修改入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住管理
     *
     * @param ids 需要删除的入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住管理信息
     *
     * @param id 入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public CheckInDetailVo detail(Long id) {

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();


        CheckIn checkIn = checkInMapper.selectCheckInById(id);

        LambdaQueryWrapper<CheckInConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(id > 0, CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(lambdaQueryWrapper);
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());


        //老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();

        checkInElderVo.setId(elder.getId());
        checkInElderVo.setName(elder.getName());
        checkInElderVo.setIdCardNo(elder.getIdCardNo());
        checkInElderVo.setBirthday(elder.getBirthday());
        checkInElderVo.setSex(elder.getSex());
        checkInElderVo.setPhone(elder.getPhone());
        checkInElderVo.setAddress(elder.getAddress());
        checkInElderVo.setImage(elder.getImage());
        checkInElderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
        checkInElderVo.setIdCardPortraitImg(elder.getIdCardPortraitImg());
        checkInElderVo.setAge(AgeUtils.calculateAge(elder.getBirthday()));


        //入住配置
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());


        checkInConfigVo.setId(checkInConfig.getId());
        checkInConfigVo.setCheckInId(checkInConfig.getCheckInId());
        checkInConfigVo.setNursingLevelId(checkInConfig.getNursingLevelId());
        checkInConfigVo.setNursingLevelName(checkInConfig.getNursingLevelName());
        checkInConfigVo.setFeeStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVo.setFeeEndDate(checkInConfig.getFeeEndDate());
        checkInConfigVo.setDeposit(checkInConfig.getDeposit());
        checkInConfigVo.setNursingFee(checkInConfig.getNursingFee());
        checkInConfigVo.setBedFee(checkInConfig.getBedFee());
        checkInConfigVo.setInsurancePayment(checkInConfig.getInsurancePayment());
        checkInConfigVo.setGovernmentSubsidy(checkInConfig.getGovernmentSubsidy());
        checkInConfigVo.setOtherFees(checkInConfig.getOtherFees());
        checkInConfigVo.setSortOrder(checkInConfig.getSortOrder());

        //签约办理
        LambdaQueryWrapper<Contract> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(elder.getId() > 0, Contract::getElderId, elder.getId());
        lambdaQueryWrapper1.eq(Contract::getStatus, 1);
        Contract contract = contractMapper.selectOne(lambdaQueryWrapper1);


        //家属信息
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);


        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;
    }

}
